<!-- 饼图 -->
<template>
  <div class="echarts-info" :style="{ height: height, width: width }" :id="'canvas-box-pic1'+number"></div>
</template>

<script lang="ts" name="BasicEchartsPie" setup>
import {getCurrentInstance, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch} from "vue";
import {debounce} from "lodash";
import {fontSizeRem} from "@/utils/baseCfg";
const { proxy } = getCurrentInstance() as any //类型可以为任意类型

const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  title: {
    type: String,
    default: "",
  },
  count:{
    type: String,
    default: '',
  },
  showLabel:{
    type: Boolean,
    default: false,
  },
  showLegend:{
    type: Boolean,
    default: true,
  },
  spe:{
    type: Boolean,
    default: true,
  },
  chartData: {
    type: Object,
    default: () => {
      return {
        name: [],
      }
    },
    required: true, //传入的报表数据
  },
  graphic:{
    type: Object,
    default: () => {
      return {
        left:0,
        top: 10,
        width: 220,
        height: 220
      }
    },
  },
})

// 报表信息
const eCharts = proxy.$ECharts
let chart = shallowRef<any>();
let colors = reactive([
  "rgba(134, 220, 251, 1)",
  "rgba(0, 255, 255, 1)",
  "rgba(108, 232, 172, 1)",
  "rgba(54, 153, 255, 1)",
  "rgba(255, 157, 85, 1)",
  "rgba(245, 212, 70, 1)",
  "rgba(255, 164, 10, 1)",
  "rgba(158, 136, 255, 1)",
  "rgba(184, 122, 1, 1)",
  "rgba(6, 70, 255, 1)",
  "rgba(245, 212, 70, 1)",
],); // pic颜色
let number = ref(Math.random() + 1); // 报表id
watch(
    () => props.chartData,
    async () => {
      await nextTick()
      initChart()
    },
    {
      deep: true
    }
)

const resizeHandler = () => {
  chart.value.resize()
}

const resizeHandlerOrigin = debounce(resizeHandler, 500)

// 初始化报表
const initChart = () =>{
  chart.value = eCharts.getInstanceByDom(document.getElementById(`canvas-box-pic1${number.value}`))
  if (chart.value === undefined) {
    chart.value = eCharts.init(document.getElementById(`canvas-box-pic1${number.value}`));
  }
  chart.value.clear();
  setOptions();
}
// 图表配置项
const setOptions = ()=> {
  const options = {
    title: {
      text: props.count,
      left: '45%',
      top:'30%',
      textStyle: { // 主标题样式
        fontSize: fontSizeRem(30),
        color: 'rgba(231, 169, 20, 1)',
        fontWeight: 'bold',
        fontFamily: 'din-bold'
      },
      subtextStyle: { // 副标题样式
        color: '#ffffff',
        fontSize: fontSizeRem(16),
      },
      textAlign: 'center'
    },
    // tooltip: {
    //   trigger: 'item',
    // },
    legend: {
      type:'scroll',
      show: props.showLegend,
      right: '0',
      top: '10%',
      orient: 'vertical',
      textStyle: {
        color: 'interit',
        fontSize: fontSizeRem(14),
        lineHeight: fontSizeRem(10),
        rich: {
          name: {
            fontSize: fontSizeRem(16),
            align: 'center',
            fontFamily:'SourceHanSansCN-Regular'
          },
          value: {
            fontSize: fontSizeRem(18),
            fontFamily:'PangMenZhengDao'
          }
        }
      },
      itemWidth: fontSizeRem(8),
      itemHeight: fontSizeRem(8),
      itemGap: fontSizeRem(15),
      formatter: (name: string) => {
        let data = options.series[0].data;
        let total = 0;
        let tarValue;
        if(data){
          for (let i = 0, l = data.length; i < l; i++) {
            total += data[i].value;
            if (data[i].name == name) {
              tarValue = data[i].value;
            }
          }
          const p = (tarValue / total * 100).toFixed(2);
          return `{name| ${name}} {value| ${p}}%`;
        }
      },
      pageTextStyle:{
        color: '#fff'
      }
    },
    color: colors,
    graphic: {
      type: 'image',
      id: 'backgroundImage',
      style: {
        image: new URL(`../assets/icons/pie-bg.png`, import.meta.url).href, // 背景图片的路径或URL
        width: fontSizeRem(props.graphic.width),  // 图片的宽度，可以设置为具体像素值或百分比
        height: fontSizeRem(props.graphic.height), // 图片的高度，可以设置为具体像素值或百分比
        opacity: 1    // 图片的透明度，范围从0（完全透明）到1（完全不透明）
      },
      left: fontSizeRem(props.graphic.left),     // 图片相对于容器左边界的距离，可以是具体像素值或百分比，或使用'center'、'left'、'right'
      top: 'center',      // 图片相对于容器上边界的距离，可以是具体像素值或百分比，或使用'center'、'top'、'bottom'
      z: -10            // 控制图形元素的堆叠顺序，值越小越先绘制，被其他元素覆盖的可能性越大
    },
    series: [
      {
        name: props.title,
        type: 'pie',
        radius: ['50%', '63%'],
        center: ['26%', '50%'],
        avoidLabelOverlap: false,
        padAngle: 2,
        label: {
          show: props.showLabel,
          formatter: '{b} {d}%',
        },
        emphasis: {
          label: {
            show: false,
            fontSize: fontSizeRem(14),
            formatter: '{b} {d}%',
          },
          itemStyle: {
            shadowBlur: 2,
            shadowOffsetX: 0,
          }
        },
        labelLine: {
          show: false
        },
        data: props.chartData
      }
    ]
  }
  chart.value.setOption(options);
}

window.addEventListener('resize', resizeHandlerOrigin)
onMounted(async () => {
  // 初始化报表
  await nextTick()
  initChart();
})

onBeforeUnmount(()=>{
  window.removeEventListener('resize', resizeHandlerOrigin)
  // 页面销毁时 销毁图表
  if (!chart) {
    return;
  }
  chart.value.dispose();
  chart.value = null;
})
</script>

<style scoped>

</style>